//
//  CommunityViewController.m
//  Four_Fit
//
//  Created by xalo on 16/7/12.
//  Copyright © 2016年 xmaz. All rights reserved.
//

#import "CommunityViewController.h"
#import <UIButton+WebCache.h>
#import "CommunityCell.h"
#import "Community.h"
#import "CommentViewController.h"
#import "CommunityUserViewController.h"
#import "ThemeViewController.h"
#import "NoteViewController.h"
#import "PublishViewController.h"
#import "DownMenu.h"
#import "MenuItem.h"

@interface CommunityViewController ()<UITableViewDelegate,UITableViewDataSource,PubishViewControllerDelegate>
/** 暂存请求数据所需的参数tokenid */
@property (nonatomic, strong) NSString *tokenid;
/** 轮播图和3个button背后的View */
@property (nonatomic, strong) UIView *backgroundView;
/** 存放scrollView图片 */
@property (nonatomic, strong) NSMutableArray *scrollArray;
/** <#注释#> */
@property (nonatomic, strong) UITableView *tableView;
/** 存放button图片 */
@property (nonatomic, strong) NSMutableArray *buttonArray;
/** 存放button文字 */
@property (nonatomic, strong) NSMutableArray *labelArray;
/** 存放button的id */
@property (nonatomic, strong) NSMutableArray *BtnIdArray;
/** 存放cell上面的模型数据 */
@property (nonatomic, strong) NSMutableArray *dataSourceArray;
/** <#注释#> */
@property (nonatomic, assign) NSInteger page;
/** 存放scrollView的id */
@property (nonatomic, strong) NSMutableArray *scrollIdArray;
/** 上次选中的索引(或者控制器) */
@property (nonatomic, assign) NSInteger lastSelectedIndex;
/** <#注释#> */
@property (nonatomic, strong) UIButton *WritringButton;

@property (nonatomic, weak) DownMenu *downMenu;

@property (nonatomic, assign) BOOL isPopMenu;
@end

static NSString *const cellID = @"community_cell";
@implementation CommunityViewController

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 108)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (NSMutableArray *)scrollArray {
    if (!_scrollArray) {
        _scrollArray = [NSMutableArray array];
    }
    return _scrollArray;
}

- (NSMutableArray *)buttonArray {
    if (!_buttonArray) {
        _buttonArray = [NSMutableArray array];
    }
    return _buttonArray;
}

- (NSMutableArray *)labelArray {
    if (!_labelArray) {
        _labelArray = [NSMutableArray array];
    }
    return _labelArray;
}
- (NSMutableArray *)BtnIdArray {
    if (!_BtnIdArray) {
        _BtnIdArray = [NSMutableArray array];
    }
    return _BtnIdArray;
}

- (NSMutableArray *)scrollIdArray {
    if (!_scrollIdArray) {
        _scrollIdArray = [NSMutableArray array];
    }
    return _scrollIdArray;
}

- (NSMutableArray *)dataSourceArray {
    if (!_dataSourceArray) {
        _dataSourceArray = [NSMutableArray array];
    }
    return _dataSourceArray;
}

- (UIView *)backgroundView {
    if (!_backgroundView) {
        _backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 305)];
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 300, self.view.frame.size.width, 5)];
        view.backgroundColor = [UIColor colorWithRed:223/255.0 green:223/255.0 blue:223/255.0 alpha:0.8];
        [_backgroundView addSubview:view];
//        [self.view addSubview:_backgroundView];
    }
    return _backgroundView;
}

- (DownMenu *)downMenu
{
    if (_downMenu == nil) {
        
        MenuItem *item = [MenuItem itemWithImage:[UIImage imageNamed:@"Development"] title:nil];
        MenuItem *item1 = [MenuItem itemWithImage:[UIImage imageNamed:@"Development"] title:nil];
        MenuItem *item2 = [MenuItem itemWithImage:[UIImage imageNamed:@"Development"] title:nil];
        MenuItem *item3 = [MenuItem itemWithImage:[UIImage imageNamed:@"Development"] title:nil];
        MenuItem *item4 = [MenuItem itemWithImage:[UIImage imageNamed:@"Development"] title:nil];
        MenuItem *item5 = [MenuItem itemWithImage:[UIImage imageNamed:@"Development"] title:nil];
        
        NSArray *items = @[item,item1,item2,item3,item4,item5];
        
        // 弹出黑色菜单
        _downMenu = [DownMenu showInView:self.view items:items oriY:0];
        
    }
    return _downMenu;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
    
    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:0.27 green:0.29 blue:0.33 alpha:1.00]];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName : [UIFont boldSystemFontOfSize:18]}];
    //view即将出现的时候，button显示
    self.WritringButton.hidden= NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = @"社区";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor colorWithRed:223/255.0 green:223/255.0 blue:223/255.0 alpha:1];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"菜单" style:UIBarButtonItemStylePlain target:self action:@selector(popMenu)];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"CommunityCell" bundle:nil] forCellReuseIdentifier:cellID];
    self.tableView.tableHeaderView = self.backgroundView;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self requestTokenid];
    [self setUpRefresh];
    //将发布button添加到window上
    [self setUpButton];
    //接收点击用户头像的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didTapUserPicture:) name:@"didTapUserPicture" object:nil];
    //接收点击scrollview的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didTapScrollView:) name:@"TapScrollView" object:nil];
    //接收tabBar按钮被点击的通知
    static NSString *tabBarDidSelectedNotification = @"tabBarDidSelectedNotification";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabBarSeleted) name:tabBarDidSelectedNotification object:nil];
}

- (void)popMenu {
    
    if (_isPopMenu == NO) {
        
        [self downMenu];
        
    }else{
        // 隐藏菜单
        [self.downMenu hide];
        
    }
    
    _isPopMenu = !_isPopMenu;
}

#pragma mark 接收到点击scrollview的通知，跳转到scrollview详情界面
- (void)didTapScrollView:(NSNotification *)note {
    
    NSInteger index = [note.userInfo[@"index"] integerValue];
    
    CommentViewController *commentVc = [[CommentViewController alloc] init];
    commentVc.noteid = self.scrollIdArray[index];
    commentVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:commentVc animated:YES];
    
}

#pragma mark 接收到用户头像被点击的通知，跳转到用户详情界面
- (void)didTapUserPicture:(NSNotification *)note {
    
    CommunityUserViewController *userVc = [[CommunityUserViewController alloc] init];
    
    userVc.userID = note.userInfo[@"userID"];
    userVc.userName = note.userInfo[@"userName"];
    
    userVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:userVc animated:YES];
}

#pragma mark 接收tabBar被点击，刷新数据
- (void)tabBarSeleted {
    
    // 如果是连续选中2次, 直接刷新
    if (self.lastSelectedIndex == self.tabBarController.selectedIndex && self.view.isShowingOnKeyWindow) {
        [self.tableView.mj_header beginRefreshing];
    }
    
    // 记录这一次选中的索引
    self.lastSelectedIndex = self.tabBarController.selectedIndex;
    
}

- (void)setUpRefresh {
    
    MJRefreshGifHeader *gifHeader = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        
//        [self.dataSourceArray removeAllObjects];
        self.page = 1;
        
        //请求tableView的数据
        [self loadTableViewDataWithPage:self.page];
        
        
    }];
    self.tableView.mj_header = gifHeader;
    [self.tableView.mj_header beginRefreshing];
    
    NSMutableArray *imageArray = [NSMutableArray array];
    for (int i = 1; i < 34; i++) {
        NSString *str = [NSString stringWithFormat:@"46-120HQ24947－%d（被拖移）.tiff",i];
        UIImage *image = [UIImage imageNamed:str];
        [imageArray addObject:image];
    }
    gifHeader.labelLeftInset = -15;
    [gifHeader setImages:imageArray duration:0.5 forState:MJRefreshStateRefreshing];
    
    MJRefreshBackGifFooter *gifFooter = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
        
        self.page += 1;
        //请求下一页数据
        [self loadTableViewDataWithPage:self.page];
        
    }];
    self.tableView.mj_footer = gifFooter;
    
    gifFooter.labelLeftInset = -15;
    [gifFooter setImages:imageArray duration:0.5 forState:MJRefreshStateRefreshing];

}

- (void)requestTokenid {
    
    [[QZRequestManager sharedManager]fetchDataWithUrl:@"http://ws.sythealth.com/ws/common/user/quicklogin?desc=IOS&mobileid=cac6e00a37a1d0549b10a69a5501fff2b38d11c5&product=fit&tokenid=tokenid_undefined&usersid=5784da4c4925c70c581758a9" parameters:@{} method:@"GET" needToCaches:NO fetchData:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
       
        self.tokenid = dic[@"data"][@"tokenid"];
        
        
        
    } updateUI:^{
        
        [self loadData];
    }];
    
    
}
//请求轮播图和button数据
- (void)loadData {
  
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"tokenid"] = self.tokenid;
    parame[@"userid"] = @"5784da4c4925c70c581758a9";
    
    
    [[QZRequestManager sharedManager] fetchDataWithUrl:@"http://ws.sythealth.com/ws/fit/v53/square/getindex" parameters:parame method:@"GET" needToCaches:NO fetchData:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//        NSLog(@"%@",dic[@"data"][@"recommendDtoList"]);
        for (NSDictionary *srollViewDic in dic[@"data"][@"recommendDtoList"]) {
            [self.scrollArray addObject:srollViewDic[@"pic"]];
            [self.scrollIdArray addObject:srollViewDic[@"relevance"]];
        }
        
        for (NSDictionary *btnDic in dic[@"data"][@"indexThemeDtoList"]) {
            [self.buttonArray addObject:btnDic[@"icon"]];
            [self.labelArray addObject:btnDic[@"name"]];
            [self.BtnIdArray addObject:btnDic[@"themeId"]];
        }
        
//       NSLog(@"%@",dic[@"data"][@"indexThemeDtoList"]);
        
        
    } updateUI:^{
        
        [self setUpButtonWithImage:self.buttonArray label:self.labelArray];
        
    }];
    
}
- (void)loadTableViewDataWithPage:(NSInteger)page {
    
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"tokenid"] = @"tokenid_undefined";
    parame[@"userid"] = @"5784da4c4925c70c581758a9";
    parame[@"page"] = @(page);
    
    [[QZRequestManager sharedManager] fetchDataWithUrl:@"http://ws.sythealth.com/ws/fit/v53/square/recommendlistv531" parameters:parame method:@"GET" needToCaches:NO fetchData:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//        NSLog(@"%@",dic[@"data"][@"feedList"]);
        NSMutableArray *tempArray = [NSMutableArray array];
        for (NSDictionary *smallDic in dic[@"data"][@"feedList"]) {
            
            Community *community = [[Community alloc] init];
            [community setValuesForKeysWithDictionary:smallDic];

            if (self.page == 1) { //如果是下拉刷新，避免重复，就覆盖数组中之前的数据
                
                [tempArray addObject:community];
                self.dataSourceArray = tempArray;
            } else {
                
                [self.dataSourceArray addObject:community];
            }
        }
        
    } updateUI:^{
       
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
        
        [self.tableView reloadData];
    }];
    
    
}

//设置button
- (void)setUpButtonWithImage:(NSArray *)imageArray label:(NSArray *)labelArray{
    //设置轮播图
    QZSliderView *scrollView = [[QZSliderView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200) AndImageArray:self.scrollArray];
    [self.backgroundView addSubview:scrollView];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 200, self.view.frame.size.width, 100)];
    view.backgroundColor = [UIColor whiteColor];
    [self.backgroundView addSubview:view];
    
    CGFloat btnW = 65;
    CGFloat Margin = (self.view.frame.size.width - btnW * 3) / 4;
    for (int i = 0; i < 3; i++) {
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(i * btnW + Margin * (i + 1), 10, btnW, btnW);
        btn.layer.cornerRadius = btn.frame.size.width * 0.5;
        btn.layer.masksToBounds = YES;
        
        btn.tag = i;
        [btn sd_setImageWithURL:[NSURL URLWithString:imageArray[i]] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(btn.frame.origin.x, 100 - btn.frame.origin.y - 11, btn.frame.size.width, 15)];
        label.text = labelArray[i];
        label.textAlignment = NSTextAlignmentCenter;
        [label setFont:[UIFont systemFontOfSize:14]];
        [label setTextColor:[UIColor darkGrayColor]];
        
        [view addSubview:btn];
        [view addSubview:label];
        
    }
    
}
- (void)clickButton:(UIButton *)btn {
    
    ThemeViewController *themeVc = [[ThemeViewController alloc] init];
    themeVc.title = self.labelArray[btn.tag];
    themeVc.themeid = self.BtnIdArray[btn.tag];

    themeVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:themeVc animated:YES];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataSourceArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommunityCell  *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    cell.community = self.dataSourceArray[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    Community *com = self.dataSourceArray[indexPath.row];
    
    return com.cellHeight;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CommentViewController *comVc = [[CommentViewController alloc] init];
    
    comVc.noteid = [self.dataSourceArray[indexPath.row] ID];
    
    comVc.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:comVc animated:YES];
    
    
}
//设置button的属性
- (void)setUpButton {
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(kWidth - 70, kHeight - 130, 50, 50)];
    self.buttonFrame = btn.frame;
    btn.layer.cornerRadius = btn.width * 0.5;
    btn.layer.masksToBounds = YES;
    
    [btn setImage:[UIImage imageNamed:@"dynamic_event"] forState:UIControlStateNormal];
    [[UIApplication sharedApplication].keyWindow addSubview:btn];
    self.WritringButton = btn;
    [self.WritringButton addTarget:self action:@selector(clickWritting) forControlEvents:UIControlEventTouchUpInside];
}
//button点击事件
- (void)clickWritting {
    
    PublishViewController *publishVc = [[PublishViewController alloc] init];
    publishVc.delegate = self;
    publishVc.view.frame = [UIScreen mainScreen].bounds;
    
    [self presentViewController:publishVc animated:YES completion:nil];
    
    self.WritringButton.hidden = YES;
}
#pragma mark - <pubishViewControllerDelegate>
- (void)pubishViewController:(UIViewController *)pubishViewController {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        self.WritringButton.hidden = NO;
    });
}
//view消失之前移除button
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.WritringButton.hidden = YES;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    self.WritringButton.hidden = NO;
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.WritringButton.hidden = YES;
}

//- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
//    if (velocity.y > 0) {
//        [self.navigationController setNavigationBarHidden:YES animated:YES];
//        [UIView animateWithDuration:0.3 animations:^{
//            self.tableView.y = -64;
//            self.tableView.height = kHeight + 20;
//        }];
//    }else{
//        [self.navigationController setNavigationBarHidden:NO animated:YES];
//        
//    }
//}
//
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    
//    if (scrollView.contentOffset.y == 0) {
//        
//        [UIView animateWithDuration:0.3 animations:^{
//            self.tableView.y = 64;
//            self.tableView.height = kHeight;
//        }];
//    }
//    
//}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
